package com.lenovo.lcdm.dcm.handler;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.lenovo.lcdm.dcm.entity.CtoCV;
import com.lenovo.lcdm.dcm.service.CtoCVService;
import com.lenovo.lcdm.integration.config.ConsumerMessageHandler;

import java.util.List;
import java.util.Map;

public class CTOCvsConsumerHandler implements ConsumerMessageHandler {
    @Override
    public void handleMessage(String msg) {
        CtoCVService ctoCVService = SpringUtil.getBean(CtoCVService.class);

        JSONObject jsonObject = JSONUtil.parseObj(msg);
        if (ObjectUtil.isNotEmpty(jsonObject.get("data"))) {
            JSONObject jsonCto = JSONUtil.parseObj(jsonObject.get("data"));
            String ctoNumber = String.valueOf(jsonCto.get("ctoNumber"));
            List<CtoCV> list = ctoCVService.lambdaQuery().eq(CtoCV::getCtoNumber, ctoNumber).list();
            if (CollectionUtil.isNotEmpty(list)) {
                List<Long> oldIds = list.stream().map(CtoCV::getId).toList();
                ctoCVService.removeBatchByIds(oldIds);
            }
            Map<String, List<String>> maps = Maps.newHashMap();
            if (ObjectUtil.isNotEmpty(jsonCto.get("cvLinks"))) {
                JSONArray charValues = JSONUtil.parseArray(jsonCto.get("cvLinks"));
                List<CtoCV> ctoCVS = charValues.stream().map(charValue -> {
                    CtoCV ctoCV = new CtoCV();
                    JSONObject jsonCharValue = JSONUtil.parseObj(charValue);
                    ctoCV.setCtoNumber(ctoNumber);
                    ctoCV.setCharname(String.valueOf(jsonCharValue.get("characteristicNumber")));
                    JSONArray values = JSONUtil.parseArray(jsonCharValue.get("charValues"));
                    List<String> charValueName = values.stream().map(obj -> StrUtil.toString(JSONUtil.parseObj(obj).get("charValueName"))).toList();
                    ctoCV.setValue(String.join(",", charValueName));
                    return ctoCV;
                }).toList();
                ctoCVService.saveBatch(ctoCVS);
            }
        }
    }
}
